<?php
/**
 *  CGException class
 *
 *  @author $Author: jinsonxu@gmail.com $:
 *  $Date: 2014-11-06 09:27:28 +0000 (Thu, 06 Nov 2014) $:
 *  $Id: CGException.php 3 2014-11-06 09:27:28Z jinsonxu@gmail.com $:
 *  @version $Rev: 3 $:
 *  @package cgenie.application
 */

//TODO: See whether we can add messages to an array in a static CGException class
//cos currently when multiple exceptions are thrown, only the last one has its message shown
//when it's caught at the root front page controller.

class CGException extends Exception {

    public function __construct($message = null, $code = 0) {
        parent::__construct($message, $code);
    }


    public function CGExit($displayErrors = true) {
        //TODO: Figure out whether is web service, if so, return xml error msg instead
        if($displayErrors) {

            $renderer = isset($_REQUEST['renderer']) ? $_REQUEST['renderer'] : 'xhtml';
            header('Cache-Control: no-cache, must-revalidate');
            header('Expires: Mon, 26 Jul 1970 05:00:00 GMT');

            if($renderer == 'xml') {
                header ("Content-Type:text/xml");
                $result = '<document>
                               <result-status>Fail</result-status>
                               <result-content>'.htmlspecialchars($this->getMessage()).'</result-content>
                           </document>';

            } else if($renderer == 'json') {
                $return = array('result-status' => 'Fail', 'result-content' => $this->getMessage());

                header('Content-type: application/json'); //change to text/plain if there're problems
                $result = json_encode($return);

            } else {
                $result = '<div id="document">
                               <div id="result-status">Fail</div>
                               <div id="result-content" class="error">'
                                 . htmlspecialchars($this->getMessage()) . '
                               </div>
                           </div>';
            }

            print $result;
        }

        $this->CGExitVerbose();
        exit;
    }


    private function CGExitVerbose() {
        $logFile = CG_BASE_PATH . DIRECTORY_SEPARATOR . 'exceptions.log';

        // Open the file to get existing content
        $current = @file_get_contents($logFile);

        //// Append
        $current .= $this->getVerboseErrorMessage();

        // Write the contents back to the file
        file_put_contents($logFile, $current);

        //Utilize log4php framework
        Logger::getLogger(__CLASS__)->fatal($this->getVerboseErrorMessage());
    }



    public function getVerboseErrorMessage() {
//        $traceString = preg_replace('/(#[0-9]+)/',"$1", $this->getTraceAsString());
        $result = 'Caught CGException: ' . date('r', time()) . "\r\n" .$this->getMessage()."\r\n".$this->getTraceAsString() . "\r\n\r\n";
        return $result;
    }
}




?>
